package com.handpay.framework.swiper;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;

import com.handpay.framework.ClientEngine;
import com.handpay.framework.swiper.IBusinessSwiper.Result;
import com.handpay.framework.swiper.IPersonalSwiper.SwipeResult;
import com.handpay.framework.swiper.IPersonalSwiper.SwipeStatus;
import com.handpay.framework.swiper.ic.IICSelectApplicationCallback;
import com.handpay.framework.upcard.UPXMLReqComposer;
import com.handpay.framework.utils.DateUtils;
import com.handpay.zztong.hp.ZZTApplication;
import com.handpay.zztong.hp.config.UMengKey;
import com.handpay.zztong.hp.config.ZZTConstant;
import com.handpay.zztong.hp.log.HPLog;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedHashMap;

/**
 * 封装业务的刷卡器接口
 * 
 * @author jmshuai
 * 
 */
class ApiSwiperImplement implements IApiSwiper {
	private static final String TAG = "ApiSwiper";
	/**
	 * 具体刷卡器
	 */
	private IBusinessSwiper mSwiper;
	/**
	 * 监听器集合
	 */
	private Hashtable<Long, ISwiperListener> mCallbacks;
	/**
	 * 刷卡器的模式
	 */
	private SwiperMode mMode = SwiperMode.NORMAL_TRANS;
	/**
	 * 刷卡器的CSN
	 */
	volatile private String mCSN;
	/*
	 * 刷卡器的过程密钥
	 */
	private String mFactor;
	/**
	 * 与刷卡器交互的线程
	 */
	private HandlerThread mHandlerThread;
	/**
	 * 处理来自业务的消息，并执行相应刷卡器操作的handler
	 */
	private Handler mHandler;

	private final int CLEAR_FACTOR = -2;

	/**
	 * 通知界面显示选择卡类型界面
	 * 
	 * @param cardTypes
	 * @param selectApplicationCallback
	 */
	@Override
	public void showSelectICApp(ArrayList<String> cardTypes, IICSelectApplicationCallback selectApplicationCallback) {
		HPLog.i(TAG, "callback size:" + mCallbacks.size());
		for (ISwiperListener listener : mCallbacks.values()) {
			listener.showSelectICApp(cardTypes, selectApplicationCallback);
		}
	}

	@Override
	public void showNoAvailableApp(Runnable r) {
		for (ISwiperListener listener : mCallbacks.values()) {
			listener.showNoAvailableApp(r);
		}
	}

	/**
	 * 通知界面，关闭卡类型界面
	 */
	@Override
	public void closeSelectICApp() {
		for (ISwiperListener listener : mCallbacks.values()) {
			listener.closeSelectICApp();
		}
	}

	@Override
	public void onBatteryLow() {
		HashMap<String, String> map = new HashMap<String, String>(4);
		map.put(UMengKey.HashMapKey.DES, "低电量");
		ZZTApplication.getApp().umengEvent(UMengKey.TipsLowBattery, map);
		for (ISwiperListener listener : mCallbacks.values()) {
			listener.onBatteryLow();
		}
	}

	class MessageHandler extends Handler {
		// callbackId只有handlerThread一个线程能够修改。而且该线程只等到刷卡器操作完成后才进行下一个操作。
		private long mCallbackId = -1;
		/**
		 * 保存刷卡器的刷卡信息
		 */
		private HashMap<String, String> mHMData = new HashMap<String, String>();
		/**
		 * 当前的操作状态
		 */
		private byte mOperationStatus = -1; // 业务状态

		public MessageHandler(Looper looper) {
			super(looper);
		}

		private int resultToStatus(Result result) {
			int status = ISwiperListener.Swiper_Error;
			switch (result) {
			case OK: {
				status = ISwiperListener.Swiper_OK;
				break;
			}
			case TIMEOUT: {
				status = ISwiperListener.Swiper_Timeout;
				break;
			}
			case CANCEL: {
				status = ISwiperListener.Swiper_Cancel;
				break;
			}
			case ERROR: {
				status = ISwiperListener.Swiper_Error;
				break;
			}
			}
			return status;
		}

		private void dealConnectMessage() {
			int getCsnTime = 0;
			do {
				ISwiperListener is = mCallbacks.get(mCallbackId);
				if (null == is) {
					break;
				}

				if (null == mSwiper || !mSwiper.isSwiperReady()) {
					is.onSwiperStatus(ISwiperListener.Status_Connect, ISwiperListener.Swiper_Error, null, false);
					break;
				}
				String csn = mSwiper.getCSN();
				getCsnTime++;
				if (TextUtils.isEmpty(csn) || csn.length() < 5) {
					if (getCsnTime <= ZZTConstant.GET_CSN_MAX_TIMES) {
						continue;
					} else {
						// 统计连接刷卡器失败
						HPLog.e("onSwiperStatus", "dealConnectMessage()连接刷卡器失败SWIPE_ERROR");
						HashMap<String, String> map = new HashMap<String, String>(4);
						map.put(UMengKey.HashMapKey.DES, "连接刷卡器失败");
						ZZTApplication.getApp().umengEvent(UMengKey.TipsConnectFailed, map);
						is.onSwiperStatus(ISwiperListener.Status_Connect, ISwiperListener.Swiper_Error, null, false);
						break;
					}
				}
				HPLog.e("onSwiperStatus", "连接成功！！！");
				ApiSwiperImplement.this.mCSN = csn;
				is.onSwiperStatus(ISwiperListener.Status_Connect, ISwiperListener.Swiper_OK, null, false);
				break;
			} while (true);
		}

		private void dealSwipeMessage() {
			SwipeResult result = mSwiper.swipeCard(mFactor, ZZTConstant.SWIPER_TIMEOUT);
			if (result == null) {
				return;
			}

			SwipeStatus status = result.mStatus;
			HPLog.i("DynamiCodeP84","status:"+status+",mNeedInputPwd:"+result.mNeedInputPwd);
			ISwiperListener is = mCallbacks.get(mCallbackId);
			if (null == is) {
				return;
			}
			switch (status) {
			case SWIPE_OK: {
				// 新版刷卡器 swipeStatus返回了银行卡卡号 !这也算是刷卡成功！
				mHMData.clear();
				if (!TextUtils.isEmpty(result.mData)) {
					mHMData.put(IBusinessSwiper.BANK_PLAIN_ACCOUNT_KEY, result.mData);
				} else if (TextUtils.isEmpty(result.mData) && SwiperMode.SUPER_TRANS == mMode) {
					HPLog.e(TAG, "superMode but no plain account!");
				}
				boolean isDownloadTrd = false;
				if (!TextUtils.isEmpty(result.mCardType)) {
					if ("2".equals(result.mCardType) || "6".equals(result.mCardType)) {
						// 该卡可能存在ic卡，提示客户改用ic卡操作
						isDownloadTrd = true;
					}
				}
				switch (mMode) {
				case NORMAL_TRANS: {
					// doInputPwd(mCallbackId);
					// 需要输入密码的时候，调用输入密码命令
//					 if (result.mNeedInputPwd) {
						is.onSwiperStatus(ISwiperListener.Status_Swipe, ISwiperListener.Swiper_OK, result.mData, isDownloadTrd);
//					 }else{
////						 dealGetBankInfoMessage();
//						 doGetBankInfo(mCallbackId);
//					 }
					break;
				}
				case SUPER_TRANS: {
					// if (ZZTConfig.ENV.BALANCE_ENQUIRE_UP) {
					// //测试银联环境用的。
					// doInputPwd(mCallbackId);
					// //需要输入密码的时候，调用输入密码命令
					// if (result.mNeedInputPwd) {
					// is.onSwiperStatus(ISwiperListener.Status_Swipe,
					// ISwiperListener.Swiper_OK, , );
					// }
					// } else {
					// is.onSwiperStatus(ISwiperListener.Status_Swipe,
					// ISwiperListener.Swiper_OK, mHMData);
					// }
					is.onSwiperStatus(ISwiperListener.Status_Swipe, ISwiperListener.Swiper_OK, result.mData, isDownloadTrd);
					break;
				}
				}
				break;
			}
			case SWIPE_CANCEL: {
				// 统计取消刷卡
				HashMap<String, String> map = new HashMap<String, String>(4);
				map.put(UMengKey.HashMapKey.DES, "取消刷卡");
				ZZTApplication.getApp().umengEvent(UMengKey.TipsCancel, map);
				is.onSwiperStatus(ISwiperListener.Status_Swipe, ISwiperListener.Swiper_Cancel, null, false);
				break;
			}
			case SWIPE_ERROR: {
				// 统计刷卡异常
				HPLog.e("onSwiperStatus", "dealSwipeMessage()统计刷卡异常SWIPE_ERROR");
				HashMap<String, String> map = new HashMap<String, String>(4);
				map.put(UMengKey.HashMapKey.DES, "刷卡异常");
				ZZTApplication.getApp().umengEvent(UMengKey.TipsSwiperErr, map);
				is.onSwiperStatus(ISwiperListener.Status_Swipe, ISwiperListener.Swiper_Error, null, false);
				break;
			}
			case SWIPE_TIMEOUT: {
				// 统计刷卡超时
				HPLog.e("onSwiperStatus", "dealSwipeMessage()统计刷卡超时SWIPE_TIMEOUT");
				HashMap<String, String> map = new HashMap<String, String>(4);
				map.put(UMengKey.HashMapKey.DES, "刷卡超时");
				ZZTApplication.getApp().umengEvent(UMengKey.TipsSwiperErr, map);
				is.onSwiperStatus(ISwiperListener.Status_Swipe, ISwiperListener.Swiper_Timeout, null, false);
				break;
			}
			}
		}

		private void dealEncryptDataMessage(String plainData, String keyIndex) {
			String encData = mSwiper.encData(plainData, keyIndex, mFactor);
			ISwiperListener is = mCallbacks.get(mCallbackId);
			if (null == is) {
				mHMData.clear();
				return;
			}
			if (TextUtils.isEmpty(encData)) {
				// 统计加密数据失败
				HashMap<String, String> map = new HashMap<String, String>(4);
				map.put(UMengKey.HashMapKey.DES, "加密数据失败");
				ZZTApplication.getApp().umengEvent(UMengKey.TipsEncryptErr, map);
				is.onSwiperStatus(ISwiperListener.Status_EncyptData, ISwiperListener.Swiper_Error, keyIndex, encData, plainData);
				return;
			}
			if (mOperationStatus == ISwiperListener.Status_InputPwdRegister) {
				// 通知用户加密后的数据（账号）
				is.onSwiperStatus(ISwiperListener.Status_EncyptData, ISwiperListener.Swiper_OK, keyIndex, encData, plainData);
				doRegisterPwdProcess2(mCallbackId);
				return;
			} else if (mOperationStatus == ISwiperListener.Status_MAC || mOperationStatus == ISwiperListener.Status_EncyptData) {
				is.onSwiperStatus(ISwiperListener.Status_EncyptData, ISwiperListener.Swiper_OK, keyIndex, encData, plainData);
				return;
			} else {
				HPLog.e(TAG, "dealEncryptDataMessage invalid status:" + mOperationStatus);
			}
		}

		private void dealRegisterPwdMessage() {
			SwipeResult result = mSwiper.registerPwd(mFactor, ZZTConstant.SWIPER_TIMEOUT);
			ISwiperListener is = mCallbacks.get(mCallbackId);
			if (null == is) {
				return;
			}
			switch (result.mStatus) {
			case SWIPE_OK: {
				is.onSwiperStatus(ISwiperListener.Status_InputPwdRegister, ISwiperListener.Swiper_OK, result.mData);
				break;
			}
			case SWIPE_CANCEL: {
				is.onSwiperStatus(ISwiperListener.Status_InputPwdRegister, ISwiperListener.Swiper_Cancel, null, false);
				break;
			}
			default: {
				// 其它情况，都当做超时处理
				is.onSwiperStatus(ISwiperListener.Status_InputPwdRegister, ISwiperListener.Swiper_Timeout, null, false);
			}
			}
		}

		private void dealAffirmAmountMessage(String amount) {
			Result result = mSwiper.affirmAmount(amount, ZZTConstant.SWIPER_TIMEOUT);
			// 如果不支持确认金额。就不存在回调函数。直接返回
			// if (!mSwiper.isSupportAffirmAmount()) {
			// return;
			// }
			ISwiperListener is = mCallbacks.get(mCallbackId);
			if (null == is) {
				return;
			}
			if (Result.OK == result) {
				if (SwiperMode.NORMAL_TRANS == mMode) {
					doSwipe(mCallbackId);
				} else if (SwiperMode.SUPER_TRANS == mMode) {
					doInputPwd(mCallbackId);
				}
			}
			is.onSwiperStatus(ISwiperListener.Status_AffirmAmount, resultToStatus(result), null, false);
		}

		@SuppressWarnings("unchecked")
		private void dealGetBankInfoMessage() {
			Hashtable<String, String> hashMap = mSwiper.getBankInfo();
			ISwiperListener is = mCallbacks.get(mCallbackId);
			if (null == is) {
				HPLog.e(TAG, "ApiSwiperImplement.Class dealGetBankInfoMessage() ISwiperListener is null");
				return;
			}
			if (null == hashMap) {
				HPLog.e(TAG, "ApiSwiperImplement.Class dealGetBankInfoMessage() hashMap is null");
				is.onSwiperStatus(mOperationStatus, resultToStatus(Result.CANCEL), null, false);
				return;
			}else {
				HPLog.i(HPLog.YL_TAG,"dealGetBankInfoMessage swiper machion"+mSwiper.toString() +" value:"+hashMap.toString());
			}
			Iterator<String> iterator = hashMap.keySet().iterator();
			while (iterator.hasNext()) {
				String temp = iterator.next();
				HPLog.i(TAG, "key:" + temp + " value:" + hashMap.get(temp));
				mHMData.put(temp, hashMap.get(temp));
			}
			// 如果是新增的消费通知,那么无论是IC或者磁条,都需要做mac,一切的一切都是为了得到mac
			// 要控制好transationType这个标记,否则很容易走错通道,就会挂掉
			if (ClientEngine.getInstance().getGlobal(IBusinessSwiper.BANK_TransactionType_KEY) != null
					&& ClientEngine.getInstance().getGlobal(IBusinessSwiper.BANK_TransactionType_KEY).equals("PurchaseAdvice")) {
				LinkedHashMap<Integer, String> linkedHashMap = new LinkedHashMap<Integer, String>();
				linkedHashMap.put(4, getFactorTime());
				if (!TextUtils.isEmpty(mHMData.get(IBusinessSwiper.BANK_MerchantID_KEY))) {
					linkedHashMap.put(5, mHMData.get(IBusinessSwiper.BANK_MerchantID_KEY));
				}
				if (!TextUtils.isEmpty(mHMData.get(IBusinessSwiper.BANK_TerminalID_KEY))) {
					linkedHashMap.put(8, mHMData.get(IBusinessSwiper.BANK_TerminalID_KEY));
				}
				if (!TextUtils.isEmpty(mHMData.get(IBusinessSwiper.BANK_OrderID_KEY))) {
					linkedHashMap.put(9, mHMData.get(IBusinessSwiper.BANK_OrderID_KEY));
				}
				if (!TextUtils.isEmpty(mHMData.get(IBusinessSwiper.BANK_TransAmount_KEY))) {
					linkedHashMap.put(11, mHMData.get(IBusinessSwiper.BANK_TransAmount_KEY));
				}
				linkedHashMap.put(16, mHMData.get(IBusinessSwiper.BANK_ACCOUNT_KEY));
				if (!TextUtils.isEmpty(mHMData.get(IBusinessSwiper.BANK_TRACK2_KEY))) {
					linkedHashMap.put(25, mHMData.get(IBusinessSwiper.BANK_TRACK2_KEY));
				}
				linkedHashMap.put(28, mCSN);
				// ic number可以为空
				if (!TextUtils.isEmpty(mHMData.get(IBusinessSwiper.BANK_ICNUMBER))) {
					linkedHashMap.put(39, mHMData.get(IBusinessSwiper.BANK_ICNUMBER));
					linkedHashMap.put(251, mHMData.get(IBusinessSwiper.BANK_DCDATA));
				}
				HPLog.i(TAG, "linkedHashMap:" + linkedHashMap.toString());
				String mac = UPXMLReqComposer.getPlainMac(linkedHashMap);
				HPLog.i(TAG, "mac:" + mac + " factor:" + mFactor);
				mac = mSwiper.encData(mac, ISwiperListener.MacDataIndex, mFactor);
				HPLog.e("fyang", "mac 出现了" + mac);
				// 计算mac时失败
				if (TextUtils.isEmpty(mac)) {
					// 统计计算mac失败
					HashMap<String, String> map = new HashMap<String, String>(4);
					map.put(UMengKey.HashMapKey.DES, "IC卡计算mac失败");
					ZZTApplication.getApp().umengEvent(UMengKey.TipsEncryptErr, map);
					is.onSwiperStatus(mOperationStatus, ISwiperListener.Swiper_Error, (HashMap<String, String>) mHMData.clone());
					mHMData.clear();
					return;
				}
				mHMData.put("mac", mac);
			} else {
				// 如果是IC卡，需要做mac
				if (!TextUtils.isEmpty(mHMData.get(IBusinessSwiper.BANK_DCDATA))) {
					// 需要做mac
					LinkedHashMap<Integer, String> linkedHashMap = new LinkedHashMap<Integer, String>(10);
					linkedHashMap.put(4, getFactorTime());
					if (!TextUtils.isEmpty(mHMData.get(IBusinessSwiper.BANK_AMOUNT_KEY))) {
						linkedHashMap.put(11, mHMData.get(IBusinessSwiper.BANK_AMOUNT_KEY));
					}
					String temp=mHMData.get(IBusinessSwiper.BANK_ACCOUNT_KEY);
					if(TextUtils.isEmpty(temp)){
						temp=mHMData.get(IBusinessSwiper.BANK_PLAIN_ACCOUNT_KEY);
					}
					linkedHashMap.put(16, temp);
					linkedHashMap.put(17, mHMData.get(IBusinessSwiper.BANK_PAN_KEY));
					if (!TextUtils.isEmpty(mHMData.get(IBusinessSwiper.BANK_TRACK2_KEY))) {
						linkedHashMap.put(25, mHMData.get(IBusinessSwiper.BANK_TRACK2_KEY));
					}
					linkedHashMap.put(28, mCSN);
					if (!TextUtils.isEmpty(mHMData.get(IBusinessSwiper.BANK_DYNAMIC_KEY))) {
						linkedHashMap.put(36, mHMData.get(IBusinessSwiper.BANK_DYNAMIC_KEY));
					}
					// ic number可以为空
					if (!TextUtils.isEmpty(mHMData.get(IBusinessSwiper.BANK_ICNUMBER))) {
						linkedHashMap.put(39, mHMData.get(IBusinessSwiper.BANK_ICNUMBER));
					}
					HPLog.e(HPLog.FDL_TAG, "-----计算MAC----");
					// 2.0.0新版 IC有效期参与Mac计算
					/*
					 * if(!TextUtils.isEmpty(mHMData.get(IBusinessSwiper.
					 * BANK_PLAIN_EXPIRE_DATE))){ HPLog.e(HPLog.FDL_TAG,
					 * "mac:正在计算IC有效期"); linkedHashMap.put(34,
					 * mHMData.get(IBusinessSwiper.BANK_PLAIN_EXPIRE_DATE)); }
					 */

					linkedHashMap.put(251, mHMData.get(IBusinessSwiper.BANK_DCDATA));
					String mac = UPXMLReqComposer.getPlainMac(linkedHashMap);
					HPLog.i(TAG, "mac:" + mac + " factor:" + mFactor);
					HPLog.e(HPLog.FDL_TAG, "mac:" + mac + " factor:" + mFactor);
					HPLog.i(TAG, "mac:正在计算Mac。。。。。。");
					mac = mSwiper.encData(mac, ISwiperListener.MacDataIndex, mFactor);
					HPLog.e(HPLog.FDL_TAG, "mac:" + mac + " factor:" + mFactor);
					// 计算mac时失败
					if (TextUtils.isEmpty(mac)) {
						// 统计计算mac失败
						HPLog.e(TAG, "IC卡，做mac 统计计算mac失败");
						HashMap<String, String> map = new HashMap<String, String>(4);
						map.put(UMengKey.HashMapKey.DES, "IC卡计算mac失败");
						ZZTApplication.getApp().umengEvent(UMengKey.TipsEncryptErr, map);
						is.onSwiperStatus(mOperationStatus, ISwiperListener.Swiper_Error, (HashMap<String, String>) mHMData.clone());
						mHMData.clear();
						return;
					}
					mHMData.put("mac", mac);
				}
			}
			is.onSwiperStatus(mOperationStatus, ISwiperListener.Swiper_OK, (HashMap<String, String>) mHMData.clone());
			mHMData.clear();
		}

		private void dealInputPwdMessage() {
			Result result;
			HPLog.i(HPLog.YL_TAG,"dealInputPwdMessage 1:");
			if (mSwiper.getSwiperModel().mSupportPwd) {
				HPLog.i(HPLog.YL_TAG,"dealInputPwdMessage 2:");
				result = mSwiper.inputPwd(mFactor, ZZTConstant.SWIPER_TIMEOUT);
				HPLog.i(HPLog.YL_TAG,"dealInputPwdMessage 3:"+result);
				dealInputPwdResult(result);
				HPLog.i(HPLog.YL_TAG,"dealInputPwdMessage 3:");
			} else {
				ISwiperListener is = mCallbacks.get(mCallbackId);
				if (null == is) {
					return;
				}
				is.onShownPwd();
			}
		}

		private void dealInputPwdResult(Result result) {
			ISwiperListener is = mCallbacks.get(mCallbackId);
			if (null == is) {
				return;
			}
			if (Result.OK == result) {
				doGetBankInfo(mCallbackId);
				return;
			}
			if (mOperationStatus == ISwiperListener.Status_InputPwdTrade) {
				// 统计输入密码出问题
				HashMap<String, String> map = new HashMap<String, String>(4);
				map.put(UMengKey.HashMapKey.DES, "没有获取到密码");
				ZZTApplication.getApp().umengEvent(UMengKey.TipsInputPwdErr, map);
				HPLog.e("onSwiperStatus", "dealInputPwdResult()连接刷卡器状态" + resultToStatus(result));
				is.onSwiperStatus(mOperationStatus, resultToStatus(result), null, false);
				return;
			}
		}

		@Override
		public void handleMessage(Message msg) {
			// 清除factor也只放在HandlerThread里做。避免被主线程清除，导致factor为空
			if (CLEAR_FACTOR == msg.what) {
				HPLog.i(TAG, "factor clear!");
				mFactor = null;
				return;
			}
			mCallbackId = msg.getData().getLong("listenerId", -1l);
			HPLog.i(TAG, "mCallbackId:"+mCallbackId + " send message " + msg.what);
			// 该callback已经没监听，直接返回
			if (null == mCallbacks.get(mCallbackId)) {
				HPLog.e(TAG, mCallbackId + " already unregister!");
				mCallbackId = -1l;
				return;
			}
			try {
				// 每条命令之间，最好睡眠300-500ms
				Thread.sleep(300);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			// check mSwiper
			if (null == mSwiper || !mSwiper.isSwiperReady()) {
				HPLog.i(TAG, "swiper error! ignore msg");
				return;
			}
			mOperationStatus = (byte) msg.what;
			HPLog.i(TAG, "mOperationStatus:"+mOperationStatus);
			switch (mOperationStatus) {
			case ISwiperListener.Status_Connect: {// 等待连接
				dealConnectMessage();
				break;
			}
			case ISwiperListener.Status_Swipe: {// 等待刷卡
				if (mFactor == null) {
					mFactor = initFactor();
				}
				dealSwipeMessage();
				break;
			}
			case ISwiperListener.Status_InputPwdRegister: {// 等待输入密码（显示密码键盘）绑卡
				boolean inputPwd = msg.getData().getBoolean("inputPwd");
				if (inputPwd) {
					dealRegisterPwdMessage();
				} else {
					if (mFactor == null) {
						mFactor = initFactor();
					}
					dealEncryptDataMessage(msg.obj.toString(), ISwiperListener.KeyDataIndex);
				}
				break;
			}
			case ISwiperListener.Status_InputPwdTrade: {// 等待输入密码（显示密码键盘）交易
				boolean bankInfo = msg.getData().getBoolean("getBankInfo");
				if (bankInfo) {
					dealGetBankInfoMessage();
				} else {
					String pwd = msg.getData().getString("pwd");

					if (TextUtils.isEmpty(pwd)) {

						dealInputPwdMessage();
					} else {
						// return from UI
						if ("0".equals(pwd)) {
							dealInputPwdResult(Result.CANCEL);
						} else if (6 == pwd.length() && TextUtils.isDigitsOnly(pwd)) {
							mSwiper.setPlainPwd(pwd);
							// 开始设置密码！
							Result result = mSwiper.inputPwd(mFactor, ZZTConstant.SWIPER_TIMEOUT);
							dealInputPwdResult(result);
						} else {
							// 暂时没有处理
						}
					}
				}
				break;
			}
			case ISwiperListener.Status_AffirmAmount: {// 等待确认金额
				if (mFactor == null) {
					mFactor = initFactor();
				}
				dealAffirmAmountMessage(msg.obj.toString());
				break;
			}
			case ISwiperListener.Status_MAC: {// 等待计算MAC
				HPLog.e("Test", "等待计算mac=====");
				if (msg.getData() == null)
					return;
				String factorParam = msg.getData().getString("factor");
				String data = msg.obj.toString();
				// doBankListMac
				if (!TextUtils.isEmpty(factorParam)) {
					mFactor = factorParam;
					data = getFactorTime() + " " + data;
				}
				dealEncryptDataMessage(data, ISwiperListener.MacDataIndex);
				break;
			}
			case ISwiperListener.Status_EncyptData: {
				dealEncryptDataMessage(msg.obj.toString(), ISwiperListener.KeyDataIndex);
				break;
			}

			}
		}
	}

	ApiSwiperImplement() {
		mHandlerThread = new HandlerThread("ApiSwiper");
		mHandlerThread.start();
		mHandler = new MessageHandler(mHandlerThread.getLooper());
		mCallbacks = new Hashtable<Long, ISwiperListener>();
	}

	public void setSwiper(IBusinessSwiper swiper) {
		mSwiper = swiper;
	}

	/**
	 * 请在开始具体业务的时候，务必设置刷卡器的模式
	 * 
	 * @param mode
	 */
	public boolean setMode(SwiperMode mode) {
		boolean result;
		// setMode是个耗时的操作.例如.所以移到非工作线程里做
		// 01-15 12:00:31.834 12131 12131 E shuai : time:-------click
		// 01-15 12:00:37.190 12131 12131 I shuai : ApiSwiper:set normal result:
		// false
		HPLog.i(HPLog.YL_TAG,"mSwiper setMode:"+mSwiper);
		if (null != mSwiper) {
			result = mSwiper.setMode(mode);
			HPLog.i(TAG, "mSwiper:"+mSwiper+" setMode :" + mode + " result: " + result);
			if (result) {
				mMode = mode;
			}
			return result;
		} else {
			return false;
		}
	}

	public String getCSN() {
		return mCSN;
	}

	/**
	 * 用于清除每次刷卡器被拔出时.清除刷卡器相关信息。
	 */
	public boolean clearSwiper(IPersonalSwiper.SwiperType swiperType) {
		if (null == swiperType || (null != mSwiper && swiperType == mSwiper.getSwiperModel().mSwiperType)) {
			mCSN = null;
			if (null != mSwiper) {
				mSwiper.closeDevice();
			}
			// mCallbacks.clear();
			mSwiper = null;
			return true;
		}
		return false;
	}

	public boolean exit() {
		HPLog.e("exit", "exit");
		mCSN = null;
		if (null != mSwiper) {
			mSwiper.closeDevice();
		}
		if (null != mCallbacks) {
			mCallbacks.clear();
		}
		if (null != mHandlerThread) {
			mHandlerThread.quit();
		}
		mSwiper = null;
		mHandlerThread = null;
		mHandler = null;
		mCallbacks = null;
		return true;
	}

	private String initFactor() {
		HPLog.e(TAG, "create factor");
		return DateUtils.formatDateToString(new Date(), "yyyyMMddHHmmss") + "80";
		// return "2014061317070880";
	}

	public String getFactor() {
		return mFactor;
	}

	/**
	 * 用于每次一个交易完成，清除加密的过程因子
	 */
	public void clearFactor() {
		HPLog.i(TAG, "send clear factor");
		Message msg = Message.obtain();
		msg.what = CLEAR_FACTOR;
		mHandler.sendMessage(msg);
	}

	/**
	 * 获取用于加密时的时间
	 * 
	 * @return
	 */
	public String getFactorTime() {
		if (null != mFactor) {
			return mFactor.substring(0, 14);
		}
		return null;
	}

	/**
	 * 连接设备
	 */
	public void doDeviceConnect(long listenId) {
		mHandler.removeMessages(ISwiperListener.Status_Connect);
		Message msg = Message.obtain();
		msg.what = ISwiperListener.Status_Connect;
		Bundle b = new Bundle();
		b.putLong("listenerId", listenId);
		msg.setData(b);
		mHandler.sendMessage(msg);
	}

	/**
	 * 注册/绑卡：加密卡号-输入密码
	 * 
	 * @param
	 */
	public void doRegisterPwd(String cardNo, long listenId) {
		mHandler.removeMessages(ISwiperListener.Status_InputPwdRegister);
		Message msg = Message.obtain();
		msg.what = ISwiperListener.Status_InputPwdRegister;
		Bundle b = new Bundle();
		b.putLong("listenerId", listenId);
		b.putBoolean("inputPwd", false);
		msg.setData(b);
		msg.obj = cardNo;
		mHandler.sendMessage(msg);
	}

	private void doRegisterPwdProcess2(long listenId) {
		Message msg = Message.obtain();
		msg.what = ISwiperListener.Status_InputPwdRegister;
		Bundle b = new Bundle();
		b.putLong("listenerId", listenId);
		b.putBoolean("inputPwd", true);
		msg.setData(b);
		mHandler.sendMessage(msg);
	}

	/**
	 * 刷卡
	 * 
	 * @param
	 */
	public void doSwipe(long listenId) {
		mHandler.removeMessages(ISwiperListener.Status_Swipe);
		Message msg = Message.obtain();
		msg.what = ISwiperListener.Status_Swipe;
		Bundle b = new Bundle();
		b.putLong("listenerId", listenId);
		msg.setData(b);
		mHandler.sendMessage(msg);
	}

	private void doGetBankInfo(long listenId) {
		Message msg = Message.obtain();
		msg.what = ISwiperListener.Status_InputPwdTrade;
		Bundle b = new Bundle();
		b.putLong("listenerId", listenId);
		b.putBoolean("getBankInfo", true);
		msg.setData(b);
		mHandler.sendMessage(msg);
	}

	public void doInputPwd(long listenId) {
		HPLog.i(HPLog.YL_TAG,"doInputPwd listenId:"+listenId);
		mHandler.removeMessages(ISwiperListener.Status_InputPwdTrade);
		Message msg = Message.obtain();
		msg.what = ISwiperListener.Status_InputPwdTrade;
		Bundle b = new Bundle();
		b.putLong("listenerId", listenId);
		b.putBoolean("getBankInfo", false);
		msg.setData(b);
		mHandler.sendMessage(msg);
	}

	/**
	 * 确认金额-刷卡-输密码
	 * 
	 * @param amount
	 */
	public void doAffirmAmount(String amount, long listenId) {
		mHandler.removeMessages(ISwiperListener.Status_AffirmAmount);
		Message msg = Message.obtain();
		msg.what = ISwiperListener.Status_AffirmAmount;
		Bundle b = new Bundle();
		b.putLong("listenerId", listenId);
		msg.setData(b);
		msg.obj = amount;
		mHandler.sendMessage(msg);
	}

	/**
	 * MAC计算
	 * 
	 * @param data
	 */
	public void doMac(String data, long listenId) {
		Message msg = Message.obtain();
		msg.what = ISwiperListener.Status_MAC;
		Bundle b = new Bundle();
		b.putLong("listenerId", listenId);
		msg.setData(b);
		msg.obj = data;
		mHandler.sendMessage(msg);
	}

	/**
	 * 查询csn关联刷卡器的mac计算
	 */
	public void doBankListMac(long listenId) {
		Message msg = Message.obtain();
		msg.what = ISwiperListener.Status_MAC;
		Bundle b = new Bundle();
		b.putLong("listenerId", listenId);
		String factor = initFactor();
		b.putString("factor", factor);
		msg.setData(b);
		if (TextUtils.isEmpty(mCSN)) {
			HPLog.i(TAG, "csn already clear. ignore");
			return;
		}
		msg.obj = mCSN;
		mHandler.sendMessage(msg);
	}

	/**
	 * MAC计算
	 * 
	 * @param data
	 */
	public void doEncryData(String data, long listenId) {
		Message msg = Message.obtain();
		msg.what = ISwiperListener.Status_EncyptData;
		Bundle b = new Bundle();
		b.putLong("listenerId", listenId);
		msg.setData(b);
		msg.obj = data;
		mHandler.sendMessage(msg);
	}

	public void registerListener(ISwiperListener is) {
		HPLog.i(TAG, "register " + is.getId());
		mCallbacks.put(is.getId(), is);
	}

	public void unRegisterListener(ISwiperListener is) {
		HPLog.i(TAG, "unregister " + is.getId());
		// 清除掉所有的messages
		mHandler.removeCallbacksAndMessages(null);
		mCallbacks.remove(is.getId());
	}



	@Override
	public boolean isSupportAffirmAmount() {
		return null != mSwiper && mSwiper.isSwiperReady() && mSwiper.getSwiperModel().mSupportAffirmAmount;
	}

	@Override
	public boolean stopOperation() {
		if (null != mSwiper) {
			return mSwiper.stopOperation();
		} else {
			return true;
		}
	}

	@Override
	public boolean isSwiperOK() {
		return null != mSwiper && mSwiper.isSwiperReady();
	}

	@Override
	public IPersonalSwiper.SwiperType getSwiperType() {
		if (null != mSwiper) {
			return mSwiper.getSwiperModel().mSwiperType;
		}
		return null;
	}

	@Override
	public SwiperModel getSwiperModel() {
		if (null != mSwiper) {
			return mSwiper.getSwiperModel();
		}
		return null;
	}

	/**
	 * 设置明文密码。用户用户从UI上设置完密码后，回调
	 * 
	 * @param pwd
	 *            为null表示取消；为六位数字字符串为密码明文；其他表示密码密文
	 * @param listenId
	 */
	@Override
	public void doSetPwd(String pwd, long listenId) {
		Message msg = Message.obtain();
		msg.what = ISwiperListener.Status_InputPwdTrade;
		Bundle b = new Bundle();
		b.putLong("listenerId", listenId);
		if (null == pwd) {
			// 置为0，表示用户取消
			pwd = "0";
		}
		b.putString("pwd", pwd);
		msg.setData(b);
		mHandler.sendMessage(msg);
	}

	@Override
	public boolean isSupportInputPwd() {
		return mSwiper.getSwiperModel().mSupportPwd;
	}

	@Override
	public boolean isSupportPrint() {
		return mSwiper.getSwiperModel().mSupportPrint;
	}

	@Override
	public boolean printBitMap(int position, Bitmap bitmap) {
		return mSwiper.printBitMap(position, bitmap);
	}

	@Override
	public boolean printString(String data) {
		return mSwiper.printString(data);
	}

	@Override
	public boolean print(String data, Bitmap bitmap) {
		return mSwiper.print(data, bitmap);
	}
}
